<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/8/9
 * Time: 11:22
 */

namespace app\index\controller;


use think\Request;
use think\Cache;
use think\Db;

use phpcvs\Csv;

class StoreManager extends Backend
{
    /**
     * 订单列表
     */
    public function index()
    {

        $data  = Request::instance()->get();
        $type  = !empty($data['type']) ? $data['type'] : 3;
        $model = db('user')
            ->field('user.user_id,user.username,se.store_name')
            ->join('store se', 'user.store_id=se.store_id');
        $list = $model->where('user.ce',1)->where('user.status',0)->order('user.user_id desc')->paginate(20);
        $css  = $list->all();
        foreach ($css as $key => $k) {
            if (isset($data['time']) && $data['time'] != '' && $data['type'] == 1) {
                $type      = 1;
                $starttime = strtotime(date('Y-m-d 00:00:00', strtotime($data['time'])));
                $enttime   = strtotime(date('Y-m-d 23:59:59', strtotime($data['time'])));

            } elseif (isset($data['start_time']) && $data['end_time'] != '' && $data['type'] == 2) {
                $starttime = strtotime(date('Y-m-d 00:00:00', strtotime($data['start_time'])));
                $enttime   = strtotime(date('Y-m-d 23:59:59', strtotime($data['end_time'])));
                $type      = 2;
            } else {
                $type      = 3;
                $starttime = strtotime(date('Y-m-d 00:00:00', time()));
                $enttime   = strtotime(date('Y-m-d 23:59:59', time()));

            }
            $argv = db('response')->where(['user_id' => $k['user_id'], 'operating' => ['between', [$starttime, $enttime]], 'assign' => ['<>', 0]])->select();
            if (count($argv) == 0) {
                $response = 0;
            } else {
                $p = 0;
                foreach ($argv as $value) {
                    if (!empty($value['assign'])) {
                        $p += $value['operating'] - $value['assign'];
                    }
                }
                $response = ($p / count($argv)) / 60;
            }
            //上门及时性
            $timeliness = db('timeliness')->where(['user_id' => $k['user_id'], 'startTime' => ['between', [$starttime, $enttime]]])->select();
            if (count($timeliness) == 0) {
                $home = 0;
            } else {
                $p1 = 0;
                foreach ($timeliness as $value) {
		  if($value['planned'] !=0){
                    $op = $value['startTime'] - $value['planned'];
                    if ($op > 0) {
                        $p1 += $op;
                    }
			}
                }
                $home = ($p1 / count($timeliness)) / 60;
            }
            //平均签单时间
            $trans = db('order')->field('order.order_id,order.assignor,cn.con_time')->join('contract cn', 'cn.orders_id=order.order_id', 'left')->where(['cn.con_time' => ['between', [$starttime, $enttime]], 'order.assignor' => $k['user_id']])->select();


            if (count($trans) == 0) {
                $average = 0;
            } else {
                $p5 = 0;
                foreach ($trans as $value) {
                    $me = db('message')->where(['type' => 6, 'order_id' => $value['order_id'], 'user_id' => $k['user_id']])->field('have')->find();
                    if (!empty($me['have'])) {
                        $p5 += $value['con_time'] - $me['have'];
                    }

                }

                $average          = ($p5 / count($trans));
                $value["hours"]   = floor(abs($average) / 3600);
                $time             = (abs($average) % 3600);
                $value["minutes"] = floor($time / 60);

                $average = $value["hours"] . "小时" . $value["minutes"] . "分";
            }

            //远程跟进频次
//            $or = db('order')->where(['assignor' => $k['user_id'], 'created_time' => ['between', [$starttime, $enttime]]])->count();
            $p6 = db('through')->where(['admin_id' => $k['user_id'], 'role' => 2, 'th_time' => ['between', [$starttime, $enttime]]])->count();

            $remotely = $p6;


            //消息使用及时性
            $me = db('message')->where(['user_id' => $k['user_id'], 'time' => ['between', [$starttime, $enttime]]])->select();
            if (count($me) == 0) {
                $message = 0;
            } else {
                $p7 = 0;
                foreach ($me as $value) {
                    if (!empty($value['have'])) {
                        $p7 += $value['have'] - $value['time'];
                    }
                }
                $message = ($p7 / count($me)) / 60;
            }
            //页面停留时长
            $stay = db('stay')->where(['user_id' => $k['user_id'], 'time' => ['between', [$starttime, $enttime]]])->select();
            if (count($stay) == 0) {
                $page = 0;
            } else {
                $p8 = 0;
                foreach ($stay as $value) {
                    if (!empty($value['endTime'])) {
                        $p8 += $value['endTime'] - $value['startTime'];
                    }

                }
                $page = ($p8 / count($stay)) / 60;
            }
            //店长活跃位置统计
            $sql  = "select `address` , count(*) AS count from `active` where user_id={$k['user_id']} AND `time` BETWEEN {$starttime} AND {$enttime} group by address order by count DESC LIMIT 1";
            $stay = db()->query($sql);
            if (count($stay) == 0) {
                $active = '';
            } else {
                $active = $stay[0]['address'];
            }
            $data["star"] = strtotime(date("Y-m-d", time()) . " 0:0:0");
            $data["end"]  = strtotime(date("Y-m-d", time()) . " 24:00:00");
            //店长在线时长统计
            $online = db('online')->where(['user_id' => $k['user_id'], 'time' => ['between', [$starttime, $enttime]]])->order('id asc')->select();
            $p9     = 0;
            if ($online) {
                for ($i = 0; $i < count($online); $i++) {

                    if ($online[$i]['type'] == 0 && $i == 0) {

                        if ($online[$i]['startTime'] == $starttime) {
                            $p9 = 0;
                        } elseif ($starttime<$online[$i]['startTime'] &&   $online[$i]['startTime']<$enttime) {
                            $p9    += $online[$i]['startTime'] - $starttime;
                        } else {
                            $Begin = date('Y-m-01', $starttime);
                            $star  = strtotime($Begin);
                            $p9    += abs($online[$i]['startTime'] - $star);
                        }

                    }

                    if ($online[$i]['type'] == 0 && $i != 0) {
//                        if(!empty($online[$i-1]['startTime']) &&  $online[$i-1]['type']==1){
//                            echo 2;
//                            $p9 += abs($online[$i]['startTime'] - $online[$i-1]['startTime']);
//
//                        }

                    } elseif ($online[$i]['type'] == 1) {
                        if (!empty($online[$i + 1]['startTime']) && $online[$i + 1]['type'] == 0) {
                            $p9 += abs($online[$i]['startTime'] - $online[$i + 1]['startTime']);
                        } elseif (empty($online[$i + 1]['startTime'])) {
                            $p9 += abs($online[$i]['startTime'] - time());

                        }
                    }

                }
            } else {
                $on = db('online')->where(['user_id' => $k['user_id'], 'time' => ['<', $enttime]])->order('id desc')->find();
                if (!empty($on) && $on['type'] == 0) {
                    $p9 = 0;
                } else {
                    $ent = date('Y-m-d h:i:s', $enttime);
                    $b   = substr($ent, 0, 10);

                    $c = date('Y-m-d');
                    if ($type == 2) {
                        $p9 = $enttime - $starttime;
                    } else if ($b == $c && ($type == 1 || $type == 3)) {

                        $p9 = time() - $starttime;
                    } else {
                        $p9 = $enttime - $starttime;
                    }

                }

            }

            $time   = $p9;
            $d      = floor($time / (3600 * 24));
            $h      = floor(($time % (3600 * 24)) / 3600);
            $m      = floor((($time % (3600 * 24)) % 3600) / 60);
            $online = $d . '天' . $h . '小时' . $m;

            //app使用时长统计
            $usageTime = db('usagetime')->where(['user_id' => $k['user_id'], 'time' => ['between', [$starttime, $enttime]]])->select();
            if (count($usageTime) == 0) {
                $app = 0;
            } else {
                $p11 = 0;
                foreach ($usageTime as $value) {
                    if (!empty($value['endTime'])) {
                        $p11 += $value['endTime'] - $value['startTime'];
                    }

                }

                $app = ($p11) / 3600;
            }
            //店长上门距离统计
            $act = db('active')->where(['user_id' => $k['user_id'], 'time' => ['between', [$starttime, $enttime]]])->select();

            $distance = 0;
            for ($i = 0; $i < count($act) - 1; $i++) {
                $distance += $this->get_distance([$act[$i]['lng'], $act[$i]['lat']], [$act[$i + 1]['lng'], $act[$i + 1]['lat']]);  // 73.734589823361

            }
            $k['response'] = round($response, 3);//接单响应时长
            $k['home']     = round(abs($home), 3);//上门及时性
            $k['quote']    = 0;//报价及时性
            $k['feedback'] = 0; //反馈及时性
            $k['next']     = 0; //下次跟进及时性
            $k['average']  = $average; //平均签单时间
            $k['remotely'] = round($remotely, 3); //远程跟进频次月
            $k['message']  = round($message, 3); //消息使用及时性
            $k['page']     = round($page, 3); //页面停留时长
            $k['active']   = $active;//店长活跃位置统计
            $k['online']   = $online;//店长在线时长统计
            $k['app']      = round($app, 3);//app使用时长统计
            $k['distance'] = round($distance, 3);//店长上门距离统计
            $k['type']     = $type;//店长上门距离统计
            $list[$key]    = $k;
        }


        return $this->fetch('index', ['list' => $list, 'type' => $type, 'starttime' => $starttime, 'enttime' => $enttime]);
    }


    public
    function cha()
    {
        $user_id = Request::instance()->post('user_id');
        if (!$user_id) {
            $this->result([], 300, '请刷新后重试');
        }
        $data["star"] = strtotime(date("Y-m-d", time()) . " 0:0:0");
        $data["end"]  = strtotime(date("Y-m-d", time()) . " 24:00:00");
        $res          = db('active')->where(['user_id' => $user_id, 'time' => ['between', [$data["star"], $data["end"]]]])->select();

        if ($res) {
            return json_data(['id' => $user_id], 200);
        }
        return json_data([], 300, '暂无数据');
    }

    public function map($user_id)
    {
        $data["star"] = strtotime(date("Y-m-d", time()) . " 0:0:0");
        $data["end"]  = strtotime(date("Y-m-d", time()) . " 24:00:00");
        $res          = db('active')->where(['user_id' => $user_id, 'time' => ['between', [$data["star"], $data["end"]]]])->field('lat,lng')->select();
        foreach ($res as $k => $v) {
            $re[$k]['name'] = '';
            $re[$k]['xy']   = [$v['lng'], $v['lat']];
        }


        return $this->fetch('map', ['admin' => $re]);

    }

    function get_distance($from, $to, $km = true, $decimal = 2)
    {
        sort($from);
        sort($to);
        $EARTH_RADIUS = 6370.996; // 地球半径系数

        $distance = $EARTH_RADIUS * 2 * asin(sqrt(pow(sin(($from[0] * pi() / 180 - $to[0] * pi() / 180) / 2), 2) + cos($from[0] * pi() / 180) * cos($to[0] * pi() / 180) * pow(sin(($from[1] * pi() / 180 - $to[1] * pi() / 180) / 2), 2))) * 1000;

        if ($km) {
            $distance = $distance / 1000;
        }

        return round($distance, $decimal);
    }

}
